package com.bawei.fuxi_service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

/**
 * 一.startService和bindService的区别
 * startService：
 * bindService：
 * 二.IntentService
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btStart;
    private Button btStop;
    private Button btBind;
    private Button btUnbind;
    private Button btPlay;
    private TwoService.TwoBinder mTwoBinder;//服务代理对象
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {//链接成功
            mTwoBinder = (TwoService.TwoBinder) service;
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {//链接失败

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btStart = (Button) findViewById(R.id.bt_start);
        btStop = (Button) findViewById(R.id.bt_stop);
        btBind = (Button) findViewById(R.id.bt_bind);
        btUnbind = (Button) findViewById(R.id.bt_unbind);
        btPlay = (Button) findViewById(R.id.bt_play);
        btStart.setOnClickListener(this);
        btStop.setOnClickListener(this);
        btBind.setOnClickListener(this);
        btUnbind.setOnClickListener(this);
        btPlay.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_start://启动服务
            {
                Intent intent = new Intent(this, OneService.class);
                startService(intent);
            }
                break;
            case R.id.bt_stop://停止服务
            {
                Intent intent = new Intent(this, OneService.class);
                stopService(intent);
            }
                break;
            case R.id.bt_bind://绑定服务
            {
                Intent intent = new Intent(this, TwoService.class);
                bindService(intent,mServiceConnection,BIND_AUTO_CREATE);
            }
            break;
            case R.id.bt_unbind://解绑服务
            {
                unbindService(mServiceConnection);
            }
            break;
            case R.id.bt_play://调用服务中的方法
            {
               mTwoBinder.playMusic();
            }
            break;

        }
    }
}